<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use think\response\Json;
use app\api\model\StoreUser as StoreUserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 商城基础信息
 * Class Store
 * @package app\api\controller
 */
class StoreUser extends Controller
{

    public function staffauth(){
        // callback.php
        $appId = 'wx72472525a3170e53';
        $appSecret = '408ae225895cae891ecf56e70937cb3e';
        $code = $_GET['code']; // 微信回调带来的code
        $state = $_GET['state']; // 之前传递的state参数
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host     = $_SERVER['HTTP_HOST'];
        $script   = $_SERVER['SCRIPT_NAME'];
        $params   = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';

        // 向微信服务器请求access_token和openid
        $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$appSecret}&code={$code}&grant_type=authorization_code";

        $response = file_get_contents($tokenUrl);
        $data = json_decode($response, true);

        if (isset($data['access_token']) && isset($data['openid'])) {
            //判断是否已被绑定过
            $StoreUserModel = new StoreUserModel();
            $rs = $StoreUserModel->where(['openid'=>$data['openid'],'is_delete'=>0])->find();
            if($rs){
                echo "<div style='height: 300px;text-align: center;padding-top: 100px;font-size: 60px;font-weight: bold;color: red'>该微信已被{$rs['user_name']}<br>绑定失败！</div>";exit;
            }
            if (!$StoreUserModel->auth(['id'=>$state,'openid'=>$data['openid']])) {
                echo "<div style='height: 300px;text-align: center;padding-top: 100px;font-size: 60px;font-weight: bold;color: red'>绑定失败！｛$StoreUserModel->getError()｝</div>";exit;
            }
            echo "<div style='height: 300px;text-align: center;padding-top: 100px;font-size: 60px;font-weight: bold;'>绑定成功！</div>";exit;
        }
        echo "<div style='height: 300px;text-align: center;padding-top: 100px;font-size: 60px;font-weight: bold;color: red'>绑定失败！</div>";exit;
    }
}